﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using BitPortal.Models;
using BitPortal.Business;
using BitPortal.Utils;

namespace BitPortal.Admin.Module.PageModule
{
    public partial class PageModuleAddEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest && !IsPostBack)
            {
                BindData(Utils.GeneralUtils.ToInt32TryParse(Request.QueryString["ModuleID"]));
            }
            BindBaseModuleCombo();
            if (IsPostBack)
            {
                LoadProperty();
            }
        }
        public void LoadProperty(int? moduleId = null)
        {
            Panel5.ContentControls.Clear();
            if (string.IsNullOrEmpty(cbBaseModule.SelectedItem.Value)) return;

            var list = Business.ModuleBLL.GetBaseModuleByID(cbBaseModule.SelectedItem.Value).BaseModuleConfigs.Where(ent => ent.AllowUserConfig == true);
            foreach (Models.BaseModuleConfig property in list)
            {
                Models.ModuleConfig value;
                switch (property.DataType)
                {
                    case "Boolean":
                        Ext.Net.Checkbox control = new Ext.Net.Checkbox() { };
                        control.ID = "property" + property.ConfigID;
                        if (moduleId != null)
                        {
                            value = property.ModuleConfigs.SingleOrDefault(ent => ent.ModuleID == (int)moduleId);
                            if (value != null)
                            {
                                control.Checked = value.Value.Equals("True") ? true : false;
                            }
                        }
                        else
                        {
                            control.Checked = property.Value.Equals("True") ? true : false;
                        }
                        control.FieldLabel = property.Name;
                        Panel5.ContentControls.Add(control);
                        break;
                    case "String":
                        Ext.Net.TextField control1 = new Ext.Net.TextField() { };
                        control1.ID = "property" + property.ConfigID;
                        if (moduleId != null)
                        {
                            value = property.ModuleConfigs.SingleOrDefault(ent => ent.ModuleID == (int)moduleId);
                            if (value != null)
                            {
                                control1.Text = value.Value;
                            }
                        }
                        else
                        {
                            control1.Text = property.Value;
                        }
                        control1.FieldLabel = property.Name;
                        Panel5.ContentControls.Add(control1);
                        break;
                    case "Text":
                        Ext.Net.HtmlEditor control2 = new Ext.Net.HtmlEditor() { };
                        control2.ID = "property" + property.ConfigID;
                        if (moduleId != null)
                        {
                            value = property.ModuleConfigs.SingleOrDefault(ent => ent.ModuleID == (int)moduleId);
                            if (value != null)
                            {
                                control2.Text = value.Value;
                            }
                        }
                        else
                        {
                            control2.Text = property.Value;
                        }
                        control2.FieldLabel = property.Name;
                        Panel5.ContentControls.Add(control2);
                        break;
                    case "Interger":
                        Ext.Net.NumberField control3 = new Ext.Net.NumberField() { };
                        control3.MinValue = 0;
                        control3.AllowDecimals = false;
                        control3.ID = "property" + property.ConfigID;
                        if (moduleId != null)
                        {
                            value = property.ModuleConfigs.SingleOrDefault(ent => ent.ModuleID == (int)moduleId);
                            if (value != null)
                            {
                                control3.Text = value.Value;
                            }
                        }
                        else
                        {
                            control3.Text = property.Value;
                        }
                        control3.FieldLabel = property.Name;
                        Panel5.ContentControls.Add(control3);
                        break;
                    case "Double":
                        Ext.Net.NumberField control4 = new Ext.Net.NumberField() { };
                        control4.MinValue = 0;
                        control4.ID = "property" + property.ConfigID;
                        if (moduleId != null)
                        {
                            value = property.ModuleConfigs.SingleOrDefault(ent => ent.ModuleID == (int)moduleId);
                            if (value != null)
                            {
                                control4.Text = value.Value;
                            }
                        }
                        else
                        {
                            control4.Text = property.Value;
                        }
                        control4.FieldLabel = property.Name;
                        Panel5.ContentControls.Add(control4);
                        break;
                    case "Datetime":
                        Ext.Net.DateField control5 = new Ext.Net.DateField() { };
                        control5.ID = "property" + property.ConfigID;
                        if (moduleId != null)
                        {
                            value = property.ModuleConfigs.SingleOrDefault(ent => ent.ModuleID == (int)moduleId);
                            if (value != null)
                            {
                                control5.Text = value.Value;
                            }
                        }
                        else
                        {
                            control5.Text = property.Value;
                        }
                        control5.FieldLabel = property.Name;
                        Panel5.ContentControls.Add(control5);
                        break;
                }
            }

        }

        protected void BindBaseModuleCombo()
        {
            cbBaseModule.Items.Clear();
            foreach (ModuleBase mb in ModuleBLL.GetAllBaseModule())
            {
                cbBaseModule.Items.Add(new Ext.Net.ListItem() { Text = mb.Description, Value = mb.ModuleBaseID.ToString() });
            }

        }

        protected void GetProperty(object sender, EventArgs e)
        {
            //LoadProperty();
        }

        protected void btnInsert_Click(object sender, DirectEventArgs e)
        {
            try
            {
                if (cbBaseModule.SelectedIndex < 0)
                {
                    throw new Exception("Bạn chưa chọn loại module!");
                }
                Models.Module m = new Models.Module()
                {
                    Name = txtName.Text,
                    ModuleBase = cbBaseModule.SelectedItem.Value.ToInt32TryParse(),
                    OnAllPage = ckOnAllPage.Checked,
                    IsEnabled = ckEnabled.Checked,
                    Position = cbPosition.SelectedItem.Value,
                    SortOrder = txtSortOrder.Text.ToInt32TryParse()
                };
                int pageID = Utils.GeneralUtils.ToInt32TryParse(Request.QueryString["PageID"]);
                if (pageID > 0) m.PageID = pageID;
                foreach (Models.ModuleConfig mcf in GetPropertyValue())
                {
                    m.ModuleConfigs.Add(mcf);
                }
                if (m.Insert() > 0)
                {
                    X.Msg.Alert("Thông báo", "Thêm module thành công!", "parent.Ext.WindowMgr.getActive().hide();parent.Ext.getCmp('" + Request.QueryString["ReloadID"] + "').getStore().reload();").Show();
                }

            }
            catch (Exception ex)
            {
                X.Msg.Alert("Có lỗi xảy ra", ex.Message).Show();
            }
        }

        protected void btnUpdate_Click(object sender, DirectEventArgs e)
        {
            try
            {
                if (cbBaseModule.SelectedIndex < 0)
                {
                    throw new Exception("Bạn chưa chọn loại module!");
                }
                ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
                int Id = txtID.Text.ToInt32TryParse();
                Models.Module m = bitEnt.Modules.SingleOrDefault(ent => ent.ModuleID == Id);
                if (m != null)
                {
                    m.Name = txtName.Text;
                    m.ModuleBase = cbBaseModule.SelectedItem.Value.ToInt32TryParse();
                    m.OnAllPage = ckOnAllPage.Checked;
                    m.IsEnabled = ckEnabled.Checked;
                    m.Position = cbPosition.SelectedItem.Value;
                    m.SortOrder = txtSortOrder.Text.ToInt32TryParse();
                };
                m.ModuleConfigs.Clear();
                foreach (Models.ModuleConfig mcf in GetPropertyValue())
                {
                    m.ModuleConfigs.Add(mcf);
                }
                if (bitEnt.SaveChanges() > 0)
                {
                    X.Msg.Alert("Thông báo", "Sửa module thành công!", "parent.Ext.WindowMgr.getActive().hide();parent.Ext.getCmp('" + Request.QueryString["ReloadID"] + "').getStore().reload();").Show();
                }

            }
            catch (Exception ex)
            {
                X.Msg.Alert("Có lỗi xảy ra", ex.Message).Show();
            }

        }

        public List<Models.ModuleConfig> GetPropertyValue()
        {
            List<Models.ModuleConfig> listPropertyValues = new List<Models.ModuleConfig>();
            foreach (var c in Panel5.ContentControls)
            {
                switch (c.GetType().Name)
                {
                    case "Checkbox":
                        Ext.Net.Checkbox ck = (Ext.Net.Checkbox)c;
                        Models.ModuleConfig property = new Models.ModuleConfig()
                        {
                            ConfigID = Convert.ToInt32(ck.ID.Substring(8)),
                            Value = ck.Checked.ToString()
                        };
                        listPropertyValues.Add(property);
                        break;
                    case "TextField":
                        Ext.Net.TextField tf = (Ext.Net.TextField)c;
                        Models.ModuleConfig property2 = new Models.ModuleConfig()
                        {
                            ConfigID = Convert.ToInt32(tf.ID.Substring(8)),
                            Value = tf.Text
                        };
                        listPropertyValues.Add(property2);
                        break;
                    case "HtmlEditor":
                        Ext.Net.HtmlEditor ed = (Ext.Net.HtmlEditor)c;
                        Models.ModuleConfig property3 = new Models.ModuleConfig()
                        {
                            ConfigID = Convert.ToInt32(ed.ID.Substring(8)),
                            Value = ed.Text
                        };
                        listPropertyValues.Add(property3);
                        break;
                    case "NumberField":
                        Ext.Net.NumberField nf = (Ext.Net.NumberField)c;
                        Models.ModuleConfig property4 = new Models.ModuleConfig()
                        {
                            ConfigID = Convert.ToInt32(nf.ID.Substring(8)),
                            Value = nf.Text
                        };
                        listPropertyValues.Add(property4);
                        break;
                }
            }
            return listPropertyValues;
        }

        public void BindData(int moduleID = 0)
        {
            if (moduleID == 0)
            {
                txtID.Text = txtSortOrder.Text = "0";
                txtName.Text = "";
                cbPosition.SelectedIndex = 0;
                cbBaseModule.SelectedIndex = -1;
                ckEnabled.Checked = true;
                ckOnAllPage.Checked = false;
                btnInsert.Hidden = false;
                btnUpdate.Hidden = true;
                return;
            }
            Models.Module m = Business.ModuleBLL.GetModuleByID(moduleID);
            if (m != null)
            {
                txtID.Text = m.ModuleID.ToString();

                txtName.Text = m.Name;
                cbBaseModule.SelectedItem.Value = m.ModuleBase.ToString();
                cbBaseModule.SetValue(m.ModuleBase.ToString());
                ckOnAllPage.Checked = m.OnAllPage;
                ckEnabled.Checked = m.IsEnabled;
                txtSortOrder.Text = m.SortOrder.ToString();
                cbPosition.SelectedItem.Value = m.Position;
                LoadProperty(m.ModuleID);

                btnInsert.Hidden = true;
                btnUpdate.Hidden = false;
                if (m.OnAllPage)
                {
                    Notification.Show(new NotificationConfig()
                        {
                             AutoHide = false,
                             Title = "Thông báo",
                             Icon = Icon.Information,
                             Html = "Bạn đang sửa Module hiển thị trên tất cả các trang!",
                             
                        });
                }
            }
        }

    }
}